/* James Goldzwig
 * Professor Peter Jamieson
 * Smart Door - ECE 387 Final Project
 * Uses OpenCV for facial detection combined with 
 * Jasper presonal assistant to create an electronic
 * doorman. 
*/

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/opencv.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>

// Method to pass argument to command line
// Primarily used for taking photos
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if(!pipe) {
return "ERROR";
}
char buffer[128];
std::string result = " ";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL) {
result += buffer;
}
}
pclose(pipe);
return result;
}

using namespace cv;
using namespace std;

// Method to read in the CSV file for face identification
// Taken from (URL)
/*static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
	std::ifstream file(filemane.c_str(), ifstream::in);
	if(!file){
		string error_message = "No valid input file was given, please check the given filename.";
		CV_Error(CV_StsBadArg, error_message);
	}
	string line, path, classlabel;
	while(getline(file, line)) {
		stringstream liness(line);
		getline(liness, path, separator);
		getline(liness, classLabel);
		if(!path.empty() && !classlabel.empty()) {
			images.push_back(imread(path,0));
			labels.push_back(atoi(classlabel.c_str()));
		}
	}*/


int main(int argc, char** argv){
	
	/*vector<Mat> images;
	vector<int> labels;
	
	try {
		read_csv("", images, labels);
	} catch(cv::Exception& e) {
		
	}*/
	
	/*VideoCapture cap;
	cap.open(0);
	if(!cap.isOpened()){
		return -1;
	}*/
	
	CascadeClassifier haar_cascade;
	haar_cascade.load("haarcascade_frontalface_default.xml");
	
	//Mat image;
	for(;;){
		exec("fswebcam -r 640x480 --no-banner image.jpeg");
		Mat image = imread("image.jpeg");
		//cap >> image;
		Mat gray;
		cvtColor(image, gray, CV_BGR2GRAY);
		vector<Rect> faces;
		haar_cascade.detectMultiScale(gray, faces);
		if(faces.size() > 0){
			std::cout << "1" << std::endl;
			// Begin python script for Jasper greeting
			exec("python boot.py");
			return 0;
		} else {
			std::cout << "0" << std::endl;
		}
		//imwrite("convertedImage.jpg", gray);
		//exec("gpicview convertedImage.jpg");
	}
	return 0;
}
